package com.zhoukx.netty.grantChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 *
 *   netty实现聊天室
 */
public class GroupChatServer {

    // 监听端口
    private  int port;

    public GroupChatServer(int port){
        this.port = port;
    }

    // 编写run方法,处理客户端请求
    public void run(){

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {


        //创建启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 获取pipepline 管道
                        ChannelPipeline pipeline = ch.pipeline();
                        // 向pipeline 中添加解码器
                        pipeline.addLast("decoder",new StringDecoder());

                        //向pipeline中添加编码器
                        pipeline.addLast("encoder",new StringEncoder());

                        // 加入自定义handler
                        pipeline.addLast(new GroupChatServerHandler());
                    }
                });

        System.out.println(" netty  服务器启动");
        ChannelFuture sync = bootstrap.bind(port).sync();

        sync.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
         new GroupChatServer(7002).run();
    }
}
